#include "CameraHandler.h"
#include <QCameraInfo>

CameraHandler::CameraHandler(QObject* par)
    : QObject(par) {
    camera = new QCamera(this);
    connect(camera, SIGNAL(error(QCamera::Error)), this, SLOT(cameraError(QCamera::Error)));

    videoSurface = new MyVideoSurface(this);

    connect(videoSurface, SIGNAL(frameAvailable(QVideoFrame)), this, SLOT(cameraImageCapture(QVideoFrame)));

    QCameraViewfinderSettings settings;

    camera->setViewfinder(videoSurface);
    camera->setCaptureMode(QCamera::CaptureVideo);

    camera->start();
}

void CameraHandler::cameraImageCapture(QVideoFrame frame)
{
    if(frame.isValid() && frame.isReadable())
    {
        QImage videoImg = QImage(frame.bits(), frame.width(), frame.height(), QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat()));

        QTransform matrix;
        matrix.rotate(180.0);

        if (videoImg.isNull()) {
            qDebug() << "empty";
        }

        emit pushImg(videoImg);
    }
    frame.unmap();
}

void CameraHandler::cameraError(QCamera::Error error)
{
    qDebug() << "Camera error occurred:" << error;
}

